package org.txazo.music.commons.lrc;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 下载LRC歌词
 * 
 * @author Tu XiaoZhou
 * @since 2013-04-12
 * 
 */
public class UploadLRC {

	private static final String STRING_HTML_1 = "</ul>";
	private static final String STRING_HTML_2 = "<br />";
	private static final String STRING_HTML_3 = "";
	private static final String STRING_HTML_4 = "[10:00.00]LRC歌词下载：www.9ilrc.com";
	private static final String STRING_HTML_5 = "<ul id=\"lrc\">";

	/**
	 * 下载LRC歌词
	 */
	public static boolean uploadLRC(String title, String artist, String fileName) {
		LRC lrc = SearchLRC.getLRC(title, artist);

		if (lrc != null) {
			if (uploadLRC(lrc.getUrl(), fileName)) {
				return true;
			}
			return false;
		}
		return false;
	}

	public static boolean uploadLRC(String lrcURL, String fileName) {
		boolean result = true;
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			URL url = new URL(lrcURL);
			br = new BufferedReader(new InputStreamReader(url.openStream()));
			bw = new BufferedWriter(new FileWriter(fileName));

			String temp = null;
			boolean flag = false;
			while ((temp = br.readLine()) != null) {
				if (flag) {
					if (temp.trim().startsWith(STRING_HTML_1)) {
						break;
					}

					if (temp.contains(STRING_HTML_2)) {
						bw.write(temp.trim().replace(STRING_HTML_2,
								STRING_HTML_3));
						bw.newLine();
					} else {
						bw.write(temp);
						bw.newLine();
						bw.write(STRING_HTML_4);
					}
				}

				if (temp.trim().startsWith(STRING_HTML_5)) {
					flag = true;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			result = false;
		} catch (IOException e) {
			e.printStackTrace();
			result = false;
		} finally {
			try {
				if (bw != null) {
					bw.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;
	}

}
